use axum::Router;
use axum::extract::Request;
use axum::middleware::Next;
use axum::response::IntoResponse;
use http::header;
use tower_http::cors::CorsLayer;

pub struct MiddleWare;

impl MiddleWare {
    pub fn create_layer(router: Router) -> Router {
        router.layer(
            tower::ServiceBuilder::new()
                .layer(axum::middleware::from_fn(mid_handler_a))
                .layer(axum::middleware::from_fn(mid_handler_b)),
        )
    }
}

async fn mid_handler_a(req: Request, next: Next) -> impl IntoResponse {
    println!("middleware a:-----------start-----------");
    println!("{:?}", req.uri());
    println!("{:?}", next);
    println!("middleware a:-----------end-----------");
    next.run(req).await
}

async fn mid_handler_b(req: Request, next: Next) -> impl IntoResponse {
    println!("middleware b:-----------start-----------");
    println!("middleware b:-----------end-----------");
    next.run(req).await
}

pub async fn middleware_cors() -> CorsLayer {
    CorsLayer::new()
        .allow_credentials(true)
        .allow_methods(vec![
            http::Method::GET,
            http::Method::POST,
            http::Method::PUT,
            http::Method::DELETE,
        ])
        .allow_headers(vec![header::ORIGIN, header::AUTHORIZATION, header::ACCEPT])
}

fn asd() {}
